package cn.itsource.ymjs.service.impl;

import cn.itsource.ymjs.api.CourseDocAPI;
import cn.itsource.ymjs.doc.CourseDoc;
import cn.itsource.ymjs.dto.CourseDto;
import cn.itsource.ymjs.entify.FitnessCourse;
import cn.itsource.ymjs.entify.FitnessCourseDetail;
import cn.itsource.ymjs.entify.FitnessCourseMarket;
import cn.itsource.ymjs.entify.FitnessCourseType;
import cn.itsource.ymjs.query.CourseQuery;
import cn.itsource.ymjs.repository.FitnessCourseRepository;
import cn.itsource.ymjs.service.IFitnessCourseService;
import cn.itsource.ymjs.util.AjaxResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Transactional
@Service
public class FitnessCourseServiceImpl extends BaseServiceImpl<FitnessCourse, CourseQuery> implements IFitnessCourseService {

    @Autowired
    private FitnessCourseDetailServiceImpl detailService;

    @Autowired
    private FitnessCourseMarketServiceImpl marketService;

    @Autowired
    private FitnessCourseRepository repository;

    @Autowired
    private CourseDocAPI courseDocAPI;

    /**======================================================================================
     * 方法描述：查询方法在父类，这个构造自己的查询条件
     ======================================================================================*/
    @Override
    protected Specification createWhereForSelectPage(CourseQuery courseQuery) {
        return new Specification<FitnessCourse>(){
            @Override
            public Predicate toPredicate(Root<FitnessCourse> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                if(courseQuery.getKeyword() != null){
                    //关键字模糊查询
                    Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%"+courseQuery.getKeyword()+"%");
                    query.where(criteriaBuilder.and(p1));
                }
                return query.getRestriction();
            }
        };
    }

    /**
     * 课程新增
     * @param dto
     * @return
     */
    @Override
    public FitnessCourse add(CourseDto dto) {
        System.out.println("--------------------"+dto);
        FitnessCourse course = dto.getCourse();
        FitnessCourseDetail courseDetail = dto.getCourseDetail();
        FitnessCourseMarket courseMarket = dto.getCourseMarket();
        course.setCourseDetail(courseDetail);
        course.setCourseMarket(courseMarket);
        detailService.insert(courseDetail);
        marketService.insert(courseMarket);
        return insert(course);
    }

    @Override
    public AjaxResult online(List<Long> ids) {
        // 1.校验 TODO
        // 2.数据库修改状态
        List<FitnessCourse> allById = repository.findAllById(ids);
        allById.forEach(course -> {
            course.setStatus(1);
            repository.saveAndFlush(course);
        });
        // 声明用来装生成的集合
        List<CourseDoc> docs = new ArrayList<>();
//        List<CourseOnlineLog> courseOnlineLogs  = new ArrayList<>();
        // 因为遍历两次,所以用普通遍历合在一起,提高效率
        for (Long id : ids) {
            // 根据id查询课程
            Optional<FitnessCourse> optional = repository.findById(id);
            FitnessCourse course = optional.get();
            CourseDoc doc = new CourseDoc();
            // 拷贝相同属性到文档
            BeanUtils.copyProperties(course,doc);
            // 设置课程类型
            FitnessCourseType courseType = course.getCourseTypeId();
//            doc.setCourseTypeName(courseType.getName());
            // 设置市场信息
            FitnessCourseMarket courseMarket = course.getCourseMarket();
            BeanUtils.copyProperties(courseMarket,doc);
            doc.setOnlineTime(new Date());
            // 将生成的文档添加到集合中
            docs.add(doc);
            // 生成上架日志 TODO
//            CourseOnlineLog log = course2OnlineLog(course);
//            courseOnlineLogs.add(log);
        }
        // 3.调用feigin接口,批量添加CourseDoc到es中保存
        courseDocAPI.batchAdd(docs);

        return AjaxResult.me();
    }

    @Override
    public AjaxResult offline(List<Long> ids) {
        // 1.校验 TODO
        // 2.数据库修改状态
        List<FitnessCourse> allById = repository.findAllById(ids);
        allById.forEach(course -> {
            course.setStatus(0);
            repository.saveAndFlush(course);
        });
        // 调用feigin接口,在es中删除
        courseDocAPI.batchDel(ids);
        return AjaxResult.me();
    }
}
